import { useCallback, useEffect } from 'react';
import type { Mapless } from '../Mapless';

type SizeProps = {
  resizable: boolean;
  mapviewRef: React.RefObject<HTMLDivElement | null>;
  mapContainer: React.RefObject<HTMLDivElement | null>;
  maplessInstanceRef: React.RefObject<Mapless | undefined>;
};

const useSize = (sizeProps: SizeProps) => {
  const { resizable, mapviewRef, mapContainer, maplessInstanceRef } = sizeProps;

  useEffect(() => {
    if (!resizable) return;
    if (
      !mapviewRef.current ||
      !mapContainer.current ||
      maplessInstanceRef.current
    )
      return;
    const resizeObserver = new ResizeObserver(() => {
      if (mapviewRef.current && mapContainer.current) {
        // const size = {
        //   width: `${mapviewRef.current.offsetWidth}px`,
        //   height: `${mapviewRef.current.offsetHeight}px`,
        // };
        // mapContainer.current.style.width = size.width;
        // mapContainer.current.style.height = size.height;
        maplessInstanceRef.current?.resize(); // 调用地图resize
      }
    });
    resizeObserver.observe(mapviewRef.current);
    return () => {
      resizeObserver.disconnect();
    };
  }, [resizable]);

  const resizeOnce = useCallback(() => {
    setTimeout(() => maplessInstanceRef.current?.resize, 0);
  }, []);

  return { resizeOnce };
};

export default useSize;
